package com.kl.controller;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.kl.domain.LogisticsStoreDTO;
import com.kl.domain.StaffDTO;
import com.kl.em.ConstantEnum;
import com.kl.em.MD5Utils;
import com.kl.em.Result;
import com.kl.entity.Role;
import com.kl.entity.Staff;
import com.kl.feign.OrderServcieFeign;
import com.kl.service.IStaffService;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
import java.util.*;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2021-10-29
 */
@RestController
@RequestMapping("/staff")
public class StaffController {
    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private IStaffService iStaffService;

    @Autowired
    private OrderServcieFeign orderServcieFeign;

//    @ApiOperation(value = "登录验证接口")
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "name", value = "员工姓名", required = true,
//                    paramType = "query", dataTypeClass = String.class),
//            @ApiImplicitParam(name = "pass", value = "员工密码", required = true,
//                    paramType = "query", dataTypeClass = String.class)
//    })
//    //登录验证
//    @GetMapping("/login")
//    public Result login(@RequestParam String name, @RequestParam String pass, HttpServletRequest request) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        Staff staff = iStaffService.selectByName(name);
//        if(staff == null){
//            return Result.build(ConstantEnum.ACCOUNT_NOT);
//        }
//        String encryptedPwd = MD5Utils.getEncryptedPwd(pass);
//        MD5Utils.validPassword(pass, staff.getPassword());
//        if(!MD5Utils.validPassword(pass, staff.getPassword())){
//            return Result.build(ConstantEnum.PASS_ERROR);
//        }
//        HttpSession session = request.getSession();
//        session.setAttribute("staff",staff);
//        String staffToken = UUID.randomUUID().toString();
//        redisTemplate.boundValueOps(staffToken).set(staff);
//        redisTemplate.boundValueOps(staffToken).expire(30, TimeUnit.MINUTES);
//        return Result.build(ConstantEnum.SUCCESS).setResult(staffToken);
//    }


    @ApiOperation(value = "登录验证接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staff", value = "员工实体类", required = true,
                    paramType = "body", dataTypeClass = Staff.class)
    })
    @RequestMapping("/login")
    public Result login(@RequestBody Staff staff, Model model){
        if (staff.getName() == null || "".equals(staff.getName()) || staff.getPassword() == null || "".equals(staff.getPassword())){

            return Result.build(ConstantEnum.ARGS_NULL);
        }
        //使用shiro的登录功能
        //1. 获取subject对象
        Subject subject = SecurityUtils.getSubject();
        //2. 将账号密码封装成token对象
        UsernamePasswordToken token = new UsernamePasswordToken(staff.getName(),staff.getPassword());
        try {
            //3. 调用subject的login方法 执行登录逻辑
            subject.login(token);
        }catch (UnknownAccountException e){
            System.err.println("账号不存在");
            return Result.build(ConstantEnum.ARGS_NULL);

        }catch (IncorrectCredentialsException e){
            System.err.println("密码错误");
            return Result.build(ConstantEnum.PASS_ERROR);
        }

        return Result.build(ConstantEnum.LOGIN_SUCCESS);
    }


    @ApiOperation(value = "增加员工接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staff", value = "员工表实体类", required = true,
                    paramType = "body", dataTypeClass = Staff.class),
            @ApiImplicitParam(name = "rids", value = "员工职位表id数组", required = true,
                    paramType = "query", dataTypeClass = Integer[].class)
    })
    @PostMapping("/addInfo")
    public Result addInfo(@RequestBody Staff staff,  Integer[] rids) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        Result result = iStaffService.addInfo(staff, rids);
        return result;
    }

    @ApiOperation(value = "员工id查询接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staffid", value = "员工id", required = true, paramType = "query"),
    })
    @GetMapping("/selectByStaffId")
    public Result<StaffDTO> selectByStaffId(@RequestParam("staffid")Long staffid){
        StaffDTO staffDTO = new StaffDTO();
        try {
            Staff staff = iStaffService.getById(staffid);
            BeanUtils.copyProperties(staff, staffDTO);
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(staffDTO);
    }

    @ApiOperation(value = "派送员查询接口")
    @GetMapping("/selectByPosition")
    public Result<List<StaffDTO>> selectByPosition(){
        List<StaffDTO> staffDTOS = null;
        try {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.eq("position",2);
            List<Staff> list = iStaffService.list(wrapper);
            String string = JSONObject.toJSONString(list);
            staffDTOS = JSONArray.parseArray(string, StaffDTO.class);
        }catch (Exception e){
            e.printStackTrace();
            return Result.build(ConstantEnum.ERROR);
        }
        return Result.build(ConstantEnum.SUCCESS).setResult(staffDTOS);
    }


    @ApiOperation(value = "跳转修改页面获取数据接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "员工id", required = true,
                    paramType = "query", dataTypeClass = Long.class)
    })
    //修改获取
    @GetMapping("/toUpdate")
    public Result toUpdate(@RequestParam("id")Long id){
        // 获取用户信息
        Staff staff = iStaffService.findStaffById(id);
        // 获取角色信息
        List<Role> roles = iStaffService.findRole();
        // 获取中间表中绑定的rid
        List<Integer> ids = iStaffService.findStaffRoleById(id);
        HashMap<String,Object> map = new HashMap<>();
        map.put("staff", staff);
        map.put("roles", roles);
        map.put("ids", ids);
        return Result.build(ConstantEnum.SUCCESS).setResult(map);
    }


    @ApiOperation(value = "修改员工和权限接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "staff", value = "员工表实体类", required = true,
                    paramType = "body", dataTypeClass = Staff.class),
            @ApiImplicitParam(name = "rids", value = "员工权限表id数组", required = true,
                    paramType = "query", dataTypeClass = Integer[].class)
    })
    @PutMapping("/updateInfo")
    public Result updateInfo(@RequestBody Staff staff, Integer[] rids){
        Result result = iStaffService.updateInfo(staff, rids);
        return result;
    }


    @ApiOperation(value = "查询所有员工接口")
    @GetMapping("/findStaff")
    public Result findStaff(){
        List<Staff> staff = iStaffService.getInfo();
        return Result.build(ConstantEnum.SUCCESS).setResult(staff);
    }

    @ApiOperation(value = "根据城市查询同城员工")
    @GetMapping("/findSameCityStaff")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "siteIdList", value = "站点ID", required = true, paramType = "query",
                    allowMultiple = true)
    })
    public Result<List<Long>> findSameCityStaff(@RequestParam("siteIdList")List<Long> siteIdList){
        System.out.println(siteIdList);
        List<Long> staffIdList = iStaffService.selectBySiteIdList(siteIdList);//通过站点id查询所有的空闲送货员
        System.out.println(staffIdList);
        return Result.build(ConstantEnum.SUCCESS).setResult(staffIdList);
    }


    @ApiOperation(value = "删除员工接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "员工id", required = true,
                    paramType = "query", dataTypeClass = Long.class)
    })
    @DeleteMapping("/deleteUserInfo")
    public Result deleteStaffById(@RequestParam("id") Long id){
        Result result = iStaffService.deleteStaffById(id);
        return result;
    }


//    @ResponseBody
//    @RequestMapping("/logon")
//    public Result sendMsg(StaffDTO staff) throws UnsupportedEncodingException, NoSuchAlgorithmException {
//        StaffDTO staff1 = iStaffService.selectByName(staff.getName());
//        if(staff1 == null){
//            return Result.build(ConstantEnum.ERROR);
//        }
//        String psw = staff.getPassword();
//        String encryptedPwd = MD5Utils.getEncryptedPwd(psw);
//        staff.setPassword(encryptedPwd);
//        String id = RandomStringUtils.randomNumeric(10);
//        staff.setId(Long.parseLong(id));
//        Result result = iStaffService.insert(staff);
//
////        rocketMQTemplate.convertAndSend("sp", sp);
//
//        return result;
//    }
}
